package com.chag.app.home.Interceptor;

import com.chag.biz.userbase.dto.AccountDTO;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: CHAG
 * Date: 2016/6/5
 * Time: 15:36
 * 管理员界面后台拦截器.
 */
public class LoginInterceptor implements HandlerInterceptor {
    private Logger logger = Logger.getLogger(getClass());
    /**
     * 不需要进行校验的URL的正则表达式
     */
    private String pattern;

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    /**
     * session失效后的拦截机制
     */
    private String redirectURL;

    public String getRedirectURL() {
        return redirectURL;
    }

    public void setRedirectURL(String redirectURL) {
        this.redirectURL = redirectURL;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("进入控制台拦截器" + request.getRequestURI());
        // 如果是例外路径则放行
        if (request.getRequestURI() != null && null != pattern && Pattern.compile(pattern).matcher(request.getRequestURI()).matches()) {
            return true;
        }

        AccountDTO loginUser = (AccountDTO) request.getSession().getAttribute("loginUser");

        if (loginUser == null) {
            response.sendRedirect(getRedirectURL());
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
